import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/mark/matching_mark_list/matching_mark_list_page.dart';
import 'package:e_reception_flutter/ui/mark/matching_or_mark/bean/mark_info_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 企业-搜索列表项
///
class CompanySearchDetailListItemWidget extends StatefulWidget {
  final CompanyDetailByTypeListItemBean itemBean;
  final BuildContext context;
  final int index;
  final ValueNotifier<String> searchPageValueNotifier;
  const CompanySearchDetailListItemWidget(
      {Key key,
        this.itemBean, this.context, this.index, this.searchPageValueNotifier,
      })
      : super(key: key);

  @override
  _CompanySearchDetailListItemWidgetState createState() => _CompanySearchDetailListItemWidgetState();
}

class _CompanySearchDetailListItemWidgetState extends State<CompanySearchDetailListItemWidget> {
  String searchDetailKey = SP_SEARCH_DETAIL+UserRepository.getInstance().getCompanyId();
  // List<CompanyDetailByTypeListItemBean> itemBeanListSearch;
  @override
  void initState() {
    // itemBeanListSearch = List<CompanyDetailByTypeListItemBean>();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () async {
          // if (itemBean?.isUnknow() ?? false) {
          //   bool result = await MatchingMarkListPage.navigatorPush(
          //       context,
          //       MarkInfoBean(
          //         picurl: itemBean?.pictureUrl,
          //         fid: itemBean?.fid,
          //       ));
          //   if (result ?? false) {
          //     //刷新
          //     CompanyDetailPageState.of(context).noticeRefreshHttp();
          //   }
          //   return;
          // }
          // if(widget.itemBean == null) {
          //   return;
          // }
          // if(widget.itemBean?.delflg=="01"){
          //   VgToastUtils.toast(context, "用户已删除");
          //   return;
          // }
          //跳转到个人详情界面，并存入缓存
          PersonDetailPage.navigatorPush(context, widget.itemBean?.fuid,
              fid:widget?.itemBean?.fid,
              pages: "CompanyDetailSearchPage");
          _setCacheUserInfo();
          // AttendRecordCalendarPage.navigatorPush(context,itemBean?.fuid);
        },
        child: _toListItemWidget(context));
  }

  ///设置缓存用户
  void _setCacheUserInfo() {
    if(widget.itemBean==null){
      return;
    }
    SharePreferenceUtil.getString(searchDetailKey).then((userJsonStr){
      List<CompanyDetailByTypeListItemBean> itemBeanListSearch = List<CompanyDetailByTypeListItemBean>();
      if(userJsonStr == null){
        itemBeanListSearch?.add(widget?.itemBean);
        String cache = jsonEncode(itemBeanListSearch);
        SharePreferenceUtil.putString(searchDetailKey, cache);
      }else{
        var listDynamic = jsonDecode(userJsonStr);
        List<Map<String ,dynamic>>  map = List<Map<String ,dynamic>>.from(listDynamic);
        // List<CompanyDetailByTypeListItemBean> M = new List();
        map.forEach((element) => itemBeanListSearch.add(CompanyDetailByTypeListItemBean.fromMap(element)));
        List<String> fuids = List<String>();
        itemBeanListSearch?.forEach((element) {
          fuids?.add(element?.fuid);
        });
        if(itemBeanListSearch?.length == 10){//如果有10个缓存并且此item不在缓存内，则替换第十个
          if(!(fuids?.toString()?.contains(widget?.itemBean?.fuid))){
            itemBeanListSearch?.insert(0, widget?.itemBean);
            itemBeanListSearch?.removeAt(10);
            String cache = jsonEncode(itemBeanListSearch);
            SharePreferenceUtil.putString(searchDetailKey, cache);
          }
        }else{
          if(!(fuids?.toString()?.contains(widget?.itemBean?.fuid))){
            // map.forEach((element) => itemBeanListSearch.add(CompanyDetailByTypeListItemBean.fromMap(element)));
            itemBeanListSearch?.add(widget?.itemBean);
            String cache = jsonEncode(itemBeanListSearch);
            SharePreferenceUtil.putString(searchDetailKey, cache);
          }
        }
      }
    });


    // SharePreferenceUtil.putString(UserRepository.getInstance().getCompanyId(), userDataBean?.fuid);
    //查询缓存，缓存中有数据，在基础上存储
    // SharePreferenceUtil.getStringList(UserRepository.getInstance().getCompanyId())
    //     .then((List<String> value) {
    //   List<String> fuids = value??[];
    //   if(fuids?.length == 10){
    //     return;
    //   }
    //   if (!(fuids.contains(widget.itemBean?.fuid))) {
    //     fuids.add(widget.itemBean?.fuid);
    //     SharePreferenceUtil.putStringList(UserRepository.getInstance().getCompanyId(), fuids);
    //   }else{
    //     return;
    //   }
    // });
  }


  Widget _toListItemWidget(BuildContext context) {
    return Container(
      height: 64,
      margin: const EdgeInsets.only(left: 15),
      child: _toMainRowWidget(context),
    );
  }

  Widget _toMainRowWidget(BuildContext context) {
    return Row(
      children: <Widget>[
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Container(
            width: 36,
            height: 36,
            child: VgCacheNetWorkImage(
              showOriginEmptyStr(widget.itemBean?.putpicurl) ??
                  showOriginEmptyStr(widget.itemBean?.napicurl ?? "") ??
                  (widget.itemBean?.pictureUrl ?? ""),
              fit: BoxFit.cover,
              imageQualityType: ImageQualityType.middleDown,
              defaultErrorType: ImageErrorType.head,
              defaultPlaceType: ImagePlaceType.head,
            ),
          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          height: 36,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: (VgStringUtils.checkAllEmpty([
              widget.itemBean?.department?.trim(),
              // itemBean?.projectname?.trim(),
              // itemBean?.city?.trim(),
              widget.itemBean?.classname?.trim(),
              // itemBean?.coursename?.trim(),
            ]))
                ? MainAxisAlignment.center
                : MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  (widget.itemBean?.isUnknow() ?? false)
                      ? Text(
                    "未知",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getMinorRedColor_F95355(),
                        fontSize: 15,
                        height: 1.2),
                  )
                      : CommonNameAndNickWidget(
                    name: widget.itemBean?.name,
                    nick: widget.itemBean?.nick,
                  ),
                  VgLabelUtils.getRoleLabel(widget.itemBean?.roleid) ?? Container(),
                  _toPhoneWidget(),
                ],
              ),
              if (!VgStringUtils.checkAllEmpty([
                widget.itemBean?.department?.trim(),
                // itemBean?.projectname?.trim(),
                // itemBean?.city?.trim(),
                widget.itemBean?.classname?.trim(),
                // itemBean?.coursename?.trim(),
              ]))
                Builder(builder: (BuildContext context) {
                  return CommonConstraintMaxWidthWidget(
                    maxWidth: ScreenUtils.screenW(context)/2,
                    child: Text(
                      // (itemBean?.isUnknow() ?? false)
                      //     ? (VgDateTimeUtils.getFormatTimeStr(
                      //             itemBean?.lastPunchTime) ??
                      //         "")
                      //     : (StringUtils.isNotEmpty(itemBean?.phone)
                      //         ? "${itemBean.phone}"
                      //         : "暂无手机号码"),
                      VgStringUtils.getSplitStr([
                        widget.itemBean?.department?.trim(),
                        //项目和城市暂时不展示
                        // itemBean?.projectname?.trim(),
                        // itemBean?.city?.trim(),
                        widget.itemBean?.classname?.trim(),
                        // itemBean?.coursename?.trim(),
                      ], symbol: "/"),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 12,
                      ),
                    ),
                  );
                }),
            ],
          ),
        ),
        Spacer(),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            //查询缓存，缓存中有数据，在基础上删除
            SharePreferenceUtil.getString(searchDetailKey).then((userJsonStr){
              if(userJsonStr == null){
                return;
              }
              var listDynamic = jsonDecode(userJsonStr);
              List<Map<String ,dynamic>>  map = List<Map<String ,dynamic>>.from(listDynamic);
              List<CompanyDetailByTypeListItemBean> M = new List();
              map.forEach((element) => M.add(CompanyDetailByTypeListItemBean.fromMap(element)));
              List<String> fuids = List<String>();
              M?.forEach((element) {
                fuids?.add(element?.fuid);
              });
              if(fuids?.toString()?.contains(widget?.itemBean?.fuid)){
                // itemBeanListSearch = M;
                for(int i = 0;i<M.length ; i++){
                  if(widget?.itemBean?.fuid == M[i]?.fuid){
                    M?.removeAt(i);
                  }
                }
                // M?.forEach((element) {
                //   if(widget?.itemBean?.fuid == element?.fuid){
                //     M?.remove(element);
                //   }
                // });
                String cache = jsonEncode(M);
                SharePreferenceUtil.putString(searchDetailKey, cache);
                VgEventBus.global.send(SearchRefreshEvent());
              }else{
                return;
              }
            });

            // SharePreferenceUtil.getStringList(UserRepository.getInstance().getCompanyId())
            //     .then((List<String> value) {
            //   List<String> fuids = value??[];
            //   if ((fuids.contains(widget.itemBean?.fuid))) {
            //     fuids.remove(widget.itemBean?.fuid);
            //     SharePreferenceUtil.putStringList(UserRepository.getInstance().getCompanyId(), fuids);
            //     VgEventBus.global.send(SearchRefreshEvent());
            //   }else{
            //     return;
            //   }
            // });

            setState(() {

            });
          },
          child: Opacity(
            opacity: widget?.searchPageValueNotifier?.value==null|| widget?.searchPageValueNotifier?.value==""?1:0 ,
            child: Container(
              padding: const EdgeInsets.symmetric(vertical: 20,horizontal: 20),
              child: Image.asset(
                "images/login_close_ico.png",
                width: 9,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _toPhoneWidget() {
    return Offstage(
      offstage: widget.itemBean.phone == null || widget.itemBean.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(widget.itemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }
}

class SearchRefreshEvent{}
